package mashibing.class6;

import util.MathUtil;

import java.util.Arrays;

/**
 * @author yujiafan
 * @version 1.0.0
 * @create 2023-03-28
 */
public class Class6_3_HeapSort {

    public static void heapSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        // O(N * logN) 生成大根堆
        for (int i = 0; i < arr.length; i++) {
            heapInsert(arr,i);
        }
//        // O(N) 生成大根堆
//        for (int i = arr.length - 1; i >= 0; i--) {
//            heapify(arr, i, arr.length);
//        }
        int heapSize = arr.length;
        MathUtil.swap(arr, 0, --heapSize);
        while (heapSize > 0) {
            heapify(arr, 0, heapSize);
            MathUtil.swap(arr, 0, --heapSize);
        }
    }

    public static void heapInsert(int[] arr,int index){
        int parentIndex = (index - 1) / 2;
        while (arr[parentIndex] < arr[index]){
            MathUtil.swap(arr,parentIndex,index);
            index = parentIndex;
            parentIndex = (index - 1) / 2;
        }
//        while (arr[index] > arr[(index - 1) / 2]) {
//            MathUtil.swap(arr, index, (index - 1) / 2);
//            index = (index - 1) / 2;
//        }
    }

    public static void heapify(int[] arr, int index, int heapSize) {
        int left = index * 2 + 1;
        while (left < heapSize) {
            int larges = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;
            larges = arr[index] < arr[larges] ? larges : index;
            if (index == larges) {
                break;
            }
            MathUtil.swap(arr,index,larges);
            index = larges;
            left = index * 2 + 1;
        }
    }

    public static void main(String[] args) {
        int[] arr = MathUtil.generateArray(20, 20);
        System.out.println(Arrays.toString(arr));
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
